package br.com.emmis.tercons;

import android.app.Activity;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.analytics.tracking.android.EasyTracker;

import org.xml.sax.SAXException;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;

import br.com.emmis.tercons.constants.Constants;
import br.com.emmis.tercons.model.Intention;
import br.com.emmis.tercons.services.CheckIntentionsService;
import br.com.emmis.tercons.util.IntentionXMLUtil;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link LoadingIntentionsFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link LoadingIntentionsFragment#newInstance} factory method to
 * create an instance of this fragment.
 *
 */
public class LoadingIntentionsFragment extends Fragment {


    private OnFragmentInteractionListener mListener;
    private EasyTracker mEasyTracker;
    private int mPrayPosition;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment LoadingIntentionsFragment.
     */

    public static LoadingIntentionsFragment newInstance() {
        LoadingIntentionsFragment fragment = new LoadingIntentionsFragment();
        return fragment;
    }
    public LoadingIntentionsFragment() {
        mPrayPosition = 0;
    }

    public void setPrayPosition(int prayPosition) {
        mPrayPosition = prayPosition;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mEasyTracker = EasyTracker.getInstance(getActivity());
    }

    @Override
    public void onStop() {
        super.onStop();
        mEasyTracker.activityStop(getActivity());
    }

    @Override
    public void onStart() {
        super.onStart();
        mEasyTracker.activityStart(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        LoadIntentionsTask loadIntentionsTask = new LoadIntentionsTask();
        loadIntentionsTask.execute();
        return inflater.inflate(R.layout.fragment_loading_intentions, container, false);
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        public void onLoadingOk(Intention intention, int position);
        public void onLoadingError();
    }

    private class LoadIntentionsTask extends AsyncTask<String, Void, Intention> {

        @Override
        protected void onPostExecute(Intention intention) {
			if(mListener == null) {
				return;
			}
            if(intention != null) {
                mListener.onLoadingOk(intention, mPrayPosition);
            } else {
                mListener.onLoadingError();
            }
        }

        @Override
        protected Intention doInBackground(String... strings) {
            byte[] buffer = new byte[90000];
            FileInputStream fis = null;
            Intention intention = null;
            try {
                fis = getActivity().openFileInput(Constants.INTENTIONS_XML_FILE);
                fis.read(buffer);
                fis.close();

                IntentionXMLUtil intentionXMLUtil = new IntentionXMLUtil(buffer);
                intention = intentionXMLUtil.getIntention(mPrayPosition);

            } catch (FileNotFoundException e) {
                CheckIntentionsService.startActionDownloadCreateDonationXML(getActivity().getApplicationContext());
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return intention;
        }

    }
}
